package com.zhongketech.sunflower.activity.me;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import com.zhongketech.sunflower.Constant;
import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.MyToast;
import com.zhongketech.sunflower.R;
import com.zhongketech.sunflower.activity.BaseActivity;
import com.zhongketech.sunflower.activity.LoginActivity;
import com.zhongketech.sunflower.activity.me.BottomDialog.OnClickDialogListener;
import com.zhongketech.sunflower.adapter.FcsContact;
import com.zhongketech.sunflower.transport.Action;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.model.ImageUrl;
import com.zhongketech.sunflower.transport.model.Parents;
import com.zhongketech.sunflower.transport.model.User;
import com.zhongketech.sunflower.transport.uitl.NetTransportUtil;
import com.zhongketech.sunflower.utils.AsyncBitmapLoader;
import com.zhongketech.sunflower.utils.AsyncBitmapLoader.ImageCallBack;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PersonalSettingActivity extends BaseActivity implements
OnClickListener {


	protected String mGender;
	protected String mBirthday;
	private TextView birthdayTextView;
	private TextView nameTextView;
	private User mUser;
	private TextView genderTextView;
	private RelativeLayout avatarLayout;
	private ImageView avatarImageView;

//	private String AVATAR_TEMP_PATH = null;
//	//			SunflowerApplication.AVATAR_TEMP_PATH
//	//			+SunflowerApplication.getmUser().getId()
//	//			+SunflowerApplication.AVATAR_NAME;
	// 请求码
	private final int REQUEST_CODE_PICK_IMAGE = 0;
	protected final int REQUEST_CODE_PHOTO_GRAPH = 1;
	private final int REQUEST_CODE_PHOTO_RESOULT = 2;
	// 标志
	private final static String TAG = "PersonalSettingActivity";
	private final String IMAGE_UNSPECIFIED = "image/*";
	private TextView phoneTextView;
	//	private UpdateAvatarCallback mUpdateAvatarCallback;
	private Uri photoUri;
	//	private UpdateMeCallback mUpdateMeCallback;

	private Handler handler ;
	private static final int UPDATE_AV = 0;
	private Bitmap avBitmap = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "PersonalSettingActivity onCreate-------->");
		setContentView(R.layout.activity_me_personal_info_detail);

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.arg1) {
				case UPDATE_AV:
					if(null != avBitmap)
						avatarImageView.setImageBitmap(avBitmap);
					break;

				default:
					break;
				}
			}
		};

		//		setCallback();
		initComponent();
		initView();
		updateUserInfo();


	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "PersonalSettingActivity onResume-------->");
		setUserInfo();
	}


	//	/**
	//	 * 设置http接口回调函数
	//	 */
	//	private void setCallback() {
	//		mUpdateAvatarCallback = new UpdateAvatarCallback();
	//		mUpdateAvatarCallback.setListener(new UpdateAvatarListener() {
	//
	//			@Override
	//			public void success(UpdateAvatarResponse updateAvatarResponse,
	//					Response response) {
	//				Log.d(TAG, "update avatar success------>");
	//				String avatar_uri = updateAvatarResponse.getImage_url();
	//				// 更新本地
	//				mUser.setAvatar_url(avatar_uri);
	//				SunflowerApplication.setmUser(mUser);
	//				// 更新服务器
	//				UpdateMe update = new UpdateMe();
	//				update.setAvatar_url(avatar_uri);
	//				ClientHttpService.getMeService().updateMe(update,mUpdateMeCallback);
	//			}
	//
	//			@Override
	//			public void failure(RetrofitError error) {
	//				Log.d(TAG, "update avatar fail------>");
	//				dismissDialog();
	//				if (error.getResponse() != null) {
	//					int statusCode = error.getResponse().getStatus();
	//					if (statusCode == 500 || statusCode == 501) {
	//						final RestError body = (RestError) error.getBodyAs(RestError.class);
	//						showNetworkErrorDialog(body.errorDetails, null);
	//					} else if (statusCode == 408) {
	//						showNetworkErrorDialog(getString(R.string.connect_overtime), null);
	//					} else {
	//						showNetworkErrorDialog(error.getMessage(), null);
	//					}
	//				}
	//			}
	//		});
	//		mUpdateMeCallback = new UpdateMeCallback();
	//		mUpdateMeCallback.setListener(new UpdateMeListener() {
	//			
	//			@Override
	//			public void sucess(UserResponse arg0, Response arg1) {
	//				Log.d(TAG, "update Me sucess------>");
	//				dismissDialog();
	//				SunflowerApplication.setmUser(arg0.getUser());
	//			}
	//			
	//			@Override
	//			public void failure(RetrofitError error) {
	//				Log.d(TAG, "update Me fail------>");
	//				dismissDialog();
	//				if (error.getResponse() != null) {
	//					int statusCode = error.getResponse().getStatus();
	//					if (statusCode == 500 || statusCode == 501) {
	//						final RestError body = (RestError) error.getBodyAs(RestError.class);
	//						showNetworkErrorDialog(body.errorDetails, null);
	//					} else if (statusCode == 408) {
	//						showNetworkErrorDialog(getString(R.string.connect_overtime), null);
	//					} else {
	//						showNetworkErrorDialog(error.getMessage(), null);
	//					}
	//				}
	//			}
	//		});
	//	}

	private void initComponent() {
		// 设置键盘隐藏
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		avatarImageView = (ImageView) findViewById(R.id.avatar_img_personal_detail);
		avatarLayout = (RelativeLayout) findViewById(R.id.personal_info_set_portrait);
		nameTextView = (TextView) findViewById(R.id.personal_info_name_str);
		birthdayTextView = (TextView) findViewById(R.id.personal_info_age_str);
		genderTextView = (TextView) findViewById(R.id.personal_info_gender_str);
		phoneTextView = (TextView) findViewById(R.id.personal_info_phone_str);

		findViewById(R.id.personal_info_set_portrait).setOnClickListener(this);
	}

	/**
	 * 从本地获取头像
	 */
	protected String getAvatarFromLocal() {
		SharedPreferences spf = getSharedPreferences("UserInfo", 0);
		return spf.getString("avatar_uri", "");
	}

	/**
	 * 初始化标题栏
	 */
	private void initView() {
		// 设置标题
		TextView actionBarTitle = (TextView) findViewById(R.id.title);
		actionBarTitle.setText("个人信息");
		//		// 设置返回键
		//		TextView actionBarBack = (TextView) findViewById(R.id.back);
		//		actionBarBack.setText(getString(R.string.me_main_title));
		//		actionBarBack.setOnClickListener(this);
		// 设置存储键
		//		TextView actionBarOther = (TextView) findViewById(R.id.other);
		//		actionBarOther.setVisibility(View.INVISIBLE);
		//		actionBarOther.setText("保存");
		//		actionBarOther.setOnClickListener(null);
	}

	/**
	 * 更新用户信息
	 */
	private void updateUserInfo() {
		String name = nameTextView.getText().toString();
		// 更新数据
		//		updateLocal(name);
		//		updateServer(name);
		AsyncBitmapLoader.getInstance().loadBitmap(avatarImageView, MyApplication.getInstance().getAvatar_url(), new ImageCallBack() {

			@Override
			public void imageLoad(ImageView imageView, Bitmap bitmap) {
				// TODO Auto-generated method stub
				if(null != bitmap)
				{
					imageView.setImageBitmap(bitmap);
				}
			}
		});
	}
	//
	//	private void updateServer(String name) {
	//		UpdateMe update = new UpdateMe();
	//		update.setName(name);
	//		update.setGender(mGender);
	//		update.setBirthday(mBirthday);
	//		ClientHttpService.getMeService().updateMe(update, mUpdateMeCallback);
	//	}
	//
	//	private void updateLocal(String name) {
	//		MyApplication.getInstance().setName(name);
	//		MyApplication.getInstance().setGender(mGender);
	//		MyApplication.getInstance().setBirthday(mBirthday);
	//		MyApplication.getInstance().setAvatar_url(mUser.getAvatar_url());
	//		MyApplication.getInstance().setPhone(mUser.getPhone());
	//		MyApplication.getInstance().setPassword(mUser.getPassword());
	////		MyApplication.getInstance().setGender(mUser.getGender());
	////		SunflowerApplication.setmUser(mUser);
	//	}

	/**
	 * 设置用户
	 */
	public void setUserInfo() {
		mUser = MyApplication.getInstance().getUser();
		String name = mUser.getName();
		String phone = mUser.getPhone();
		String gender = mUser.getGender();
		String birthday = mUser.getBirthday();
		String avatar_uri = mUser.getAvatar_url();

		if (mUser != null) {
			nameTextView.setText(name);
			phoneTextView.setText(phone);
			if(birthday!=null){
				if(birthday.length()<=10){
					birthdayTextView.setText(birthday);
				}else{
					birthdayTextView.setText(mUser.getBirthday().substring(0, 10));
				}
			}

			setMyGender(gender);
			setMyAvatar(avatar_uri);
		}
	}
	//
	//	private void setMyBirthday(String birthday) {
	//		String age = Utils.getAgetFromBirthday(birthday);
	//		birthdayTextView.setText(age);
	//	}

	private void setMyAvatar(String avatar_uri) {
		// 获取头像，有就缓存
		//		Bitmap bitmap = BitmapFactory
		//				.decodeFile(AVATAR_TEMP_PATH);
		//		if (bitmap != null) {
		//			avatarImageView.setImageBitmap(bitmap);
		//		} else {
		//			ExUtils.loadImage(URLHelper.getAbsoluteUrl(avatar_uri),
		//					R.drawable.unkown_person, avatarImageView);
		//		}
	}

	public String cacheAvatar(Bitmap bitmap) {
		LogUtil.e(TAG, "保存图片");
		String url = Constant.ROOT_ADDR+UUID.randomUUID().toString()+".png";
		File f = new File(url);
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
			LogUtil.i(TAG, "已经保存");
			return url;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}
	//
	private void setMyGender(String gender) {
		if("male".equals(gender))
		{
			genderTextView.setText("男");
		}
		else if("female".equals(gender))
		{
			genderTextView.setText("女");
		}
		else
		{
			genderTextView.setText(gender);
		}
	}

	public void modifyPhone(View view) {
				startActivity(new Intent(this, ModifyPhoneActivity.class));
	}

	public void modifyPassword(View view) {
				startActivity(new Intent(this, ModifyPasswordActivity.class));
	}

	public void modifyName(View view) {
				Intent intent = new Intent(this, ModifyNameActivity.class);
				String name = nameTextView.getText().toString();
				intent.putExtra("userName", name);
				startActivity(intent);
	}

	public void modifyGender(View view){
				Intent intent = new Intent(this, ModifyGenderActivity.class);
				String gender = genderTextView.getText().toString();
				intent.putExtra("gender", gender);
				startActivity(intent);
	}

	public void modifyBirthday(View view){
				Intent intent = new Intent(this, ModifyBirthDayActivity.class);
				String birthday = birthdayTextView.getText().toString();
				intent.putExtra("birthday", birthday);
				startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.personal_info_set_portrait:
			showPicSelectMode();
			break;
		default:
			break;
		}
	}

	private void showPicSelectMode() {
		//		BottomDialog dialog = new BottomDialog(this,
		//				R.style.MyDialogBottomNormal);
		BottomDialog dialog = new BottomDialog(this,
				R.style.MyDialogStyle);
		dialog.setmTitle("个人信息");
		String str[] = new String[3];
		str[0] = "从相册选择";
		str[1] = "使用手机拍照";
		str[2] = "取消";
		dialog.setItemNames(str);
		dialog.setOnClickDialogListener(new OnClickDialogListener() {

			@Override
			public void onClick(int index) {
				switch (index) {
				case 0:// 从相片选择
					getImageFromAlbum();
					break;
				case 1:// 使用手机照相
					takePhoto();
					break;
				case 2:// 取消键
					break;
				default:
					break;
				}
			}
		});
		dialog.show();
	}

	/**
	 * 拍照获取图片
	 */
	private void takePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		ContentValues values = new ContentValues();
		photoUri = this.getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
		startActivityForResult(intent, REQUEST_CODE_PHOTO_GRAPH);
	}

	/**
	 * 从相册获取图片
	 */
	protected void getImageFromAlbum() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");// 相片类型
		startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtil.i("ZK", "onActivityResult requestCode:"+requestCode+" resultCode:"+resultCode+" data:"+data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case REQUEST_CODE_PICK_IMAGE:
				Uri uri = data.getData();
				if (uri == null) {
					MyToast.getInstance().show("无法获取图片");
					return;
				}
				handleAlbumPic(uri);
				break;
			case REQUEST_CODE_PHOTO_GRAPH:
				startPhotoZoom(photoUri);
				break;
			case REQUEST_CODE_PHOTO_RESOULT:
				handleCameraPic(data);
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void handleAlbumPic(Uri uri) {
		String img_path = getPicPathByUri(uri);
		String path = img_path;
		//		String path = this.getCacheDir().getPath() + "/" + System.currentTimeMillis() + ".jpg";
		//		try {
		//			ImageUtils.resampleImageAndSaveToNewLocation(img_path, path);
		//		} catch (Exception e) {
		//			path = img_path;
		//			e.printStackTrace();
		//		}
		// 设置头像
		LogUtil.i("ZK", "handleAlbumPic path:"+path);
		avBitmap = AsyncBitmapLoader.getInstance().getSmallBitmap(BitmapFactory.decodeFile(path));
		path = cacheAvatar(avBitmap);
		upLoadAvatar(path);
		//		cacheAvatar(bitmap);
	}

	private void upLoadAvatar(final String path) {
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setCanceledOnTouchOutside(false);
		pd.setMessage("正在上传...");
		pd.show();

		//		File file = new File(path);

		new Thread(new Runnable() {
			public void run() {
				Looper.prepare();
				ImageUrl imageurl = NetTransportUtil.uploadimage(Constant.IMGAGE_SERVER+"/index.php/images",path);
				pd.dismiss();
				if(null != imageurl && null != imageurl.getImage_url())
				{
					LogUtil.i("ZK", "new imageurl:"+imageurl.getImage_url());
					User tmpUser = mUser;
					tmpUser.setAvatar_url(imageurl.getImage_url());
					User newUser = new Action().ModifyMe(mUser);
					if(null != newUser)
					{
						final Message msg = new Message();
						msg.arg1 = UPDATE_AV;
						handler.sendMessage(msg);
						newUser.setPassword(mUser.getPassword());
						MyApplication.getInstance().SetUser(newUser);
						mUser = newUser;
						MyToast.getInstance().show("上传成功");
					}

				}
				else
				{
					MyToast.getInstance().show("上传失败");
				}
			}
		}).start();



	}

	private String getPicPathByUri(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
		int actual_image_column_index = actualimagecursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		return actualimagecursor.getString(actual_image_column_index);
	}

	/**
	 * 处理拍照的图片
	 */
	public void handleCameraPic(Intent data) {
		Uri uri = data.getData();
		if (uri == null) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				avBitmap = AsyncBitmapLoader.getInstance().getSmallBitmap(photo);
				String url = cacheAvatar(avBitmap);
				upLoadAvatar(url);
			}
		} else {
			handleAlbumPic(uri);
		}
	}

	/**
	 * 
	 * 收缩图片
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 500);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_PHOTO_RESOULT);
	}
}
